<template>
  <div class="common-table">
    <div class="table-item">
      <formItem title="名称">
        <template v-slot:rightText>
          <span>{{ formObj.title }}</span>
        </template>
      </formItem>
      <formItem title="位置">
        <template v-slot:rightText>
          <span>{{ formObj.landLocation }}</span>
        </template>
      </formItem>
      <formItem title="面积">
        <template v-slot:rightText>
          <span>{{ formObj.landArea }}</span>
        </template>
      </formItem>
    </div>
    <div class="table-item">
      <formItem title="区镇">
        <template v-slot:rightText>
          <span>{{ formObj.town }}</span>
        </template>
      </formItem>
      <formItem title="类型">
        <template v-slot:rightText>
          <span>{{ formObj.type }}</span>
        </template>
      </formItem>
      <formItem title="用途">
        <template v-slot:rightText>
          <span>{{ formObj.class }}</span>
        </template>
      </formItem>
    </div>
    <div class="table-item-two">
      <formItem title="三净地收储">
        <template v-slot:right>
          <div class="table-item-check">
            <el-checkbox v-model="checked1" label="地上净"/>
            <el-checkbox v-model="checked2" label="地下净"/>
            <el-checkbox v-model="checked3" label="权属净"/>
          </div>
        </template>
      </formItem>
      <formItem title="收储号">
        <template v-slot:right>
          <div class="table-item-input-btn">
            <div>
              <el-input v-model="formObj.code" placeholder="请输入收储号"></el-input>
            </div>
          </div>
        </template>
      </formItem>
    </div>
    <div class="table-item-two">
      <formItem title="协议签署">
        <template v-slot:right>
          <el-select v-model="formObj.sign" popper-class="big-screnn-popper" placeholder="请选择">
            <el-option
                v-for="item in useOption"
                :key="item.value"
                :label="item.value"
                :value="item.value"
            />
          </el-select>
        </template>
      </formItem>
      <formItem title="收储材料">
        <template v-slot:right>
          <el-select :class="selectClass" v-model="formObj.fileState" popper-class="big-screnn-popper" placeholder="请选择">
            <el-option
                v-for="item in typeOption"
                :key="item.value"
                :label="item.value"
                :value="item.value"
            />
          </el-select>
        </template>
      </formItem>
    </div>
    <div class="progress-table-header table-2">
      <span>收储文件填写</span>
    </div>
    <div class="table-item">
      <formItem title="乙方">
        <template v-slot:right>
          <el-input v-model="formObj.name" placeholder="请输入名称" type="text"/>
        </template>
      </formItem>
      <formItem title="位置">
        <template v-slot:right>
          <el-input v-model="formObj.location" placeholder="请输入位置" type="text"/>
        </template>
      </formItem>
      <formItem title="面积">
        <template v-slot:right>
          <el-input v-model="formObj.area" placeholder="请输入面积" type="text"/>
        </template>
      </formItem>
    </div>
    <div class="table-item">
      <formItem title="地址">
        <template v-slot:right>
          <el-input v-model="formObj.place" placeholder="请输入地址" type="text"/>
        </template>
      </formItem>
      <formItem title="法定代表人">
        <template v-slot:right>
          <el-input v-model="formObj.legal" placeholder="请输入法定代表人" type="text"/>
        </template>
      </formItem>
      <formItem title="乙方地块信息提交时间">
        <template v-slot:right>
          <el-date-picker
              v-model="formObj.submitTime"
              type="date"
              placeholder="选择日期"
              format="YYYY年MM月DD日"
              value-format="YYYY年MM月DD日"
          />
        </template>
      </formItem>
    </div>
    <div class="table-item">
      <formItem title="甲方整备期限">
        <template v-slot:right>
          <el-date-picker
              v-model="formObj.inspectTime"
              type="date"
              placeholder="选择日期"
              format="YYYY年MM月DD日"
              value-format="YYYY年MM月DD日"
          />
        </template>
      </formItem>
      <formItem title="甲方前期整备项目数">
        <template v-slot:right>
          <el-input v-model="formObj.number" placeholder="请输入名称" type="text"/>
        </template>
      </formItem>
    </div>
    <div class="table-item">
      <div class="table-full-text">
        <div class="left">
          <span>临时收储文件</span>
        </div>
        <div class="right">
          <div class="red-line">
            <el-button type="primary" @click="createFile">生成文件*</el-button>
            <el-button type="primary" @click="download(1)">下载</el-button>
            <el-button type="primary" @click="preview(1)">预览</el-button>
          </div>
        </div>
      </div>
    </div>
    <div class="table-item">
      <div class="table-full-text">
        <div class="left">
          <span>收储文件</span>
        </div>
        <div class="right">
          <div class="red-line">
            <div class="red-line-text">
              <el-input v-model="formObj.fileName" placeholder="请输入名称" type="text"/>
            </div>
            <el-upload
                action='api/upload/report'
                method="post"
                :http-request="passUrl"
                :show-file-list="false"
            >
              <el-button type="primary">上传</el-button>
            </el-upload>
            <div class="delete">
              <el-button type="primary" @click="deleteWord">取消上传</el-button>
              <el-button type="primary" @click="preview(2)">预览</el-button>
              <el-button type="primary" @click="download(2)">下载</el-button>
            </div>

          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import {reactive, defineComponent, getCurrentInstance, onMounted, watch, ref, computed} from 'vue'
import formItem from "@/components/commonFomItem/index.vue";
import {useRouter} from "vue-router";
import {ElNotification} from "element-plus";
import Data from "../../../public/config/data.json";

export default defineComponent({
  components: {formItem},
  props: ['confirmState', 'index', 'PassState', 'userName'],
  emits: ['receiveStateId'],
  setup(props) {
    const userType = localStorage.getItem("userType");
    const loginName = localStorage.getItem("loginName");
    //获取当前时间
    const getCurrentTime = () => {
      let date = new Date();
      //年
      let year = date.getFullYear().toString();
      //月份是从0月开始获取的，所以要+1;
      let month = ''
      if ((date.getMonth() + 1) < 10) {
        month = '0' + (date.getMonth() + 1).toString()
      } else {
        month = (date.getMonth() + 1).toString()
      }
      //日
      let day = date.getDate().toString();
      //时
      let hour = date.getHours().toString();

      return year + '年' + month + '月' + day + '日' + hour + '时'
    }
    //地上
    const checked1 = ref(false)
    //地下
    const checked2 = ref(false)
    //权属
    const checked3 = ref(false)
    const threeLand =reactive(['0','0','0'])
    //获取三净地情况
    const getThreeLand =(str :string)=>{
      checked1.value = str.slice(0, 1) === '1'
      checked2.value = str.slice(1, 2) === '1'
      checked3.value = str.slice(2, 3) === '1'
    }
    //设置三净地情况
    const setThreeLand =()=>{
      threeLand[0] = checked1.value === true?'1':'0'
      threeLand[1] = checked2.value === true?'1':'0'
      threeLand[2] = checked3.value === true?'1':'0'
      // console.log(threeLand)
    }
    const typeOption = reactive(Data).fileStore
    const useOption = reactive(Data).sign
    const formObj = reactive({
      name: '',
      landLocation: '',
      location: '',
      place:'',
      legal:'',
      area: '',
      type: '',
      submitTime: '',
      planTime: '',
      inspectTime: '',
      number: '',
      town: '',
      class: '',
      title: '',
      code: '',
      sign: '',
      fileState: '',
      landArea: '',
      url: '',
      path: '',
      fileName: '',
      num: '',
      threeLand:''
    })
    const router = useRouter();
    const selectClass = computed(() => {
      let defaultClass = ''
      switch (formObj.fileState) {
        case '已完成':
          defaultClass = 'red'
          break;
        case '已报，材料缺':
          defaultClass = 'orange'
          break;
        default:
          break;
      }
      return `customer-select-color${defaultClass}`
    })

    //浏览内容
    const preview = (index) => {
      if (formObj.path === '') {
        ElNotification({
          title: '预览文件',
          message: "文件地址有问题，请检查文件",
          type: 'warning',
          position: 'top-left',
          offset: 300,
        })
      } else {
        if (index === 1) {
          // resolve新窗口打开
          const newPage = router.resolve({
            path: '/preview',  // 跳转的页面路由
            query: { // 要传的参数
              url: formObj.path,
              index: props.index
            }
          })
          window.open(newPage.href, '_blank') // 打开新的窗口(跳转路径，跳转类型)
        } else {
          const newPage = router.resolve({
            path: '/preview',  // 跳转的页面路由
            query: { // 要传的参数
              url: formObj.url + '//' + formObj.fileName,
              index: props.index
            }
          })
          window.open(newPage.href, '_blank') // 打开新的窗口(跳转路径，跳转类型)
        }
      }
    }
    //下载文件
    const download = (index) => {
      if (index === 1) {
        appContext.config.globalProperties.axios({
          url: `api/downloadWord`,
          method: 'post',
          data: formObj,
          transformRequest: [function () {
            let oMyForm = new FormData();
            oMyForm.append("landId", props.index);
            oMyForm.append("path", formObj.path);
            return oMyForm;
          }],
          responseType: "blob",
        }).then((response) => {
          let blob = new Blob([response.data], {type: "application/msword;"}); // 为blob设置文件类型，这里以.xlsx为例
          let url = window.URL.createObjectURL(blob); // 创建一个临时的url指向blob对象
          let a = document.createElement("a");
          a.href = url;
          a.download = "土地收储及管理协议-"+formObj.town +"("+formObj.title +")";
          a.click();
          // 释放这个临时的对象url
          window.URL.revokeObjectURL(url);
        }).catch(() => {
          ElNotification({
            title: '下载文件',
            message: "文件未生成，请生成文件",
            type: 'warning',
            position: 'top-left',
            offset: 300,
          })
        })
      } else {
        appContext.config.globalProperties.axios({
          url: `api/downloadWord`,
          method: 'post',
          data: formObj,
          transformRequest: [function () {
            let oMyForm = new FormData();
            oMyForm.append("landId", props.index);
            oMyForm.append("path", formObj.url + '//' + formObj.fileName);
            return oMyForm;
          }],
          responseType: "blob",
        }).then((response) => {
          let blob = new Blob([response.data], {type: "application/msword;"}); // 为blob设置文件类型，这里以.xlsx为例
          let url = window.URL.createObjectURL(blob); // 创建一个临时的url指向blob对象
          let a = document.createElement("a");
          a.href = url;
          a.download = "土地收储及管理协议-"+formObj.town +"("+formObj.title +")";
          a.click();
          // 释放这个临时的对象url
          window.URL.revokeObjectURL(url);
        }).catch(() => {
          ElNotification({
            title: '下载文件',
            message: "文件未生成，请生成文件",
            type: 'warning',
            position: 'top-left',
            offset: 300,
          })
        })
      }

    }

    //传送url
    const passUrl = (Option) => {
      appContext.config.globalProperties.axios({
        url: `api/upload/agreement`,
        method: 'post',
        data: formObj,
        transformRequest: [function () {
          let oMyForm = new FormData();
          oMyForm.append("file", Option.file);
          oMyForm.append("landId", props.index);
          oMyForm.append("infoDate", getCurrentTime());
          oMyForm.append("userType",userType);
          oMyForm.append("content", loginName +"于"+getCurrentTime()+"，在"+formObj.title+"地块收储协议阶段上传了");
          return oMyForm;
        }]
      }).then((response) => {
        formObj.url = response.data
        formObj.fileName = Option.file.name
        ElNotification({
          title: '上传文件',
          message: "上传成功",
          type: 'success',
          position: 'top-left',
          offset: 300,
        })
      })
    }
    //删除文件
    const deleteWord = () => {
      if (formObj.fileName === '' || formObj.name === '') {
        ElNotification({
          title: '删除文件',
          message: "文件未上传，请上传文件",
          type: 'warning',
          position: 'top-left',
          offset: 300,
        })
      } else {
        appContext.config.globalProperties.axios({
          url: `api/delete/word`,
          method: 'post',
          data: formObj,
          transformRequest: [function () {
            let oMyForm = new FormData();
            oMyForm.append("path", formObj.url);
            oMyForm.append("name", formObj.fileName);
            return oMyForm;
          }]
        }).then(() => {
          formObj.url = ''
          formObj.fileName = ''
          ElNotification({
            title: '删除文件',
            message: "删除成功",
            type: 'success',
            position: 'top-left',
            offset: 300,
          })
        })
      }
    }

    //创建文件
    const createFile = () => {
      appContext.config.globalProperties.axios({
        url: `api/create/agreement`,
        method: 'post',
        data: formObj,
        transformRequest: [function () {
          let oMyForm = new FormData();
          oMyForm.append("code", formObj.code);
          oMyForm.append("fileName", formObj.name);
          oMyForm.append("location", formObj.location);
          oMyForm.append("place", formObj.place);
          oMyForm.append("people", formObj.legal);
          oMyForm.append("number", formObj.number);
          oMyForm.append("area", formObj.area);
          oMyForm.append("timSubmit", formObj.submitTime);
          oMyForm.append("timeInspect", formObj.inspectTime);
          oMyForm.append("landId", props.index);
          return oMyForm;
        }]
      }).then((response) => {
        formObj.path = response.data
        ElNotification({
          title: '创建文件',
          message: "创建成功",
          type: 'success',
          position: 'top-left',
          offset: 300,
        })
      })
    }

    //确定键
    watch(() => props.confirmState, () => {
      setThreeLand()
      pushData()
    })
    const pushData = () => {
      appContext.config.globalProperties.axios({
        url: `api/update/agreement`,
        method: 'post',
        data: formObj,
        transformRequest: [function () {
          let oMyForm = new FormData();
          oMyForm.append("landId", props.index);
          oMyForm.append("sign", formObj.sign);
          oMyForm.append("fileState", formObj.fileState);
          oMyForm.append("code", formObj.code);
          oMyForm.append("fileUrl", formObj.url);
          oMyForm.append("name", formObj.name);
          oMyForm.append("location", formObj.location);
          oMyForm.append("area", formObj.area);
          oMyForm.append("submitTime", formObj.submitTime);
          oMyForm.append("threeLand", threeLand[0]+threeLand[1]+threeLand[2]);
          oMyForm.append("inspectTime", formObj.inspectTime);
          oMyForm.append("number", formObj.number);
          oMyForm.append("filePath", formObj.path);
          oMyForm.append("fileName", formObj.fileName);
          oMyForm.append("place", formObj.place);
          oMyForm.append("people", formObj.legal);
          return oMyForm;
        }]
      }).then(() => {
        ElNotification({
          title: '修改数据',
          message: "修改成功",
          type: 'success',
          position: 'top-left',
          offset: 300,
        })
      })
    }


    //通过键
    watch(() => props.PassState, () => {
      setThreeLand()
      passData()
    })
    const passData = () => {
      appContext.config.globalProperties.axios({
        url: `api/pass/agreement/1`,
        method: 'post',
        data: formObj,
        transformRequest: [function () {
          let oMyForm = new FormData();
          oMyForm.append("landId", props.index);
          oMyForm.append("sign", formObj.sign);
          oMyForm.append("fileState", formObj.fileState);
          oMyForm.append("code", formObj.code);
          oMyForm.append("fileUrl", formObj.url);
          oMyForm.append("name", formObj.name);
          oMyForm.append("location", formObj.location);
          oMyForm.append("area", formObj.area);
          oMyForm.append("threeLand", threeLand[0]+threeLand[1]+threeLand[2]);
          oMyForm.append("submitTime", formObj.submitTime);
          oMyForm.append("inspectTime", formObj.inspectTime);
          oMyForm.append("number", formObj.number);
          oMyForm.append("filePath", formObj.path);
          oMyForm.append("fileName", formObj.fileName);
          oMyForm.append("place", formObj.place);
          oMyForm.append("people", formObj.legal);
          return oMyForm;
        }]
      })
    }

    const reload = () => {
      appContext.config.globalProperties.axios.post(`api/landSearch/${props.index}`).then((response) => {
        response.data.forEach(item => {
          formObj.class = item.landType
          formObj.title = item.bz
          formObj.town = item.town
          formObj.landLocation = item.landLoc
          formObj.landArea = item.landArea
          formObj.type = item.type
        })
      })
      appContext.config.globalProperties.axios.post(`api/search/agreement/${props.index}`).then((response) => {
        response.data.forEach(item => {
          formObj.sign = item.sign
          formObj.fileState = item.fileState
          formObj.code = item.code
          formObj.url = item.fileUrl
          formObj.name = item.name
          formObj.location = item.location
          formObj.area = item.area
          formObj.submitTime = item.submitTime
          formObj.inspectTime = item.inspectTime
          formObj.threeLand = item.threeLand
          formObj.number = item.number
          formObj.path = item.filePath
          formObj.fileName = item.fileName
          formObj.place = item.place
          formObj.legal = item.people
        })
        getThreeLand(formObj.threeLand)
      })
    }

    // watch(() => props.newState, () => {
    //   reload()
    // })
    //初始化地块数据
    const {appContext} = getCurrentInstance();
    onMounted(() => {
      reload()
    })

    return {
      typeOption,
      useOption,
      formObj,
      createFile,
      pushData,
      passData,
      download,
      passUrl,
      preview,
      deleteWord,
      getCurrentTime,
      checked1,
      checked2,
      checked3,
      selectClass
    }
  }

})
</script>


<style  lang="scss">
.progress-table {
  .progress-table-header {
    font-size: 16px;
    color: rgba(240, 245, 255, 0.95);
    margin: 18px 0;
    text-align: center;

    &.table-2 {
      margin-bottom: 24px;
    }
  }
}

.common-table {
  .table-item-two {
    display: flex;
    align-items: center;
    justify-content: space-around;
    margin-bottom: 20px;
    .common-form-item{
      .customer-select-colororange {
        .el-input__inner {
          color: #F7A95D;
        }
      }
      .customer-select-colorred {
        .el-input__inner {
          color:red;
        }
      }
    }
    .table-item-check {
      display: flex;

      .el-checkbox {
        color: #e9e9e9;
      }
    }
  }

  .table-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;

    .table-full-text {
      display: flex;
      width: 100%;
      align-items: center;

      .left {
        color: rgba(240, 245, 255, 0.95);
        padding-right: 10px;
        width: 61px;
      }

      .right {
        flex: 1;

        .red-line {
          display: flex;

          .red-line-text {
            padding-right: 12px;
            color: #e9e9e9;
          }

          .el-input {
            --el-input-text-color: #ffffff;
          }

          .delete {
            margin-left: 20px;
          }
        }
      }
    }

  }

  .empty-form-item {
    width: 280px;
  }

  .tips-text {
    margin-left: 62px;
    margin-top: -16px;
  }

  .table-item-input-btn {
    position: relative;

    .el-radio {
      --el-radio-text-color: #edffff;
    }

    .float-btn {
      position: absolute;
      right: 2px;
      top: 0;
    }
  }
}
</style>
